/**
 * 主JavaScript文件
 * 作为应用程序的入口点，初始化所有组件和功能
 */

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', () => {
    // 初始化各个组件
    initComponents();
    
    // 初始化路由
    initRouter();
    
    // 设置全局事件监听器
    setupGlobalListeners();
    
    // 处理页面特定逻辑
    handlePageSpecificLogic();
    
    // 初始化页面加载动画
    initPageTransition();
});

/**
 * 初始化所有组件
 */
function initComponents() {
    console.log('Initializing components...');
    
    // 初始化头部组件
    if (window.HeaderComponent) {
        try {
            const header = new window.HeaderComponent();
            header.init();
            window.appHeader = header;
            console.log('Header component initialized');
        } catch (error) {
            console.error('Error initializing header component:', error);
        }
    }
    
    // 初始化页脚组件
    if (window.FooterComponent) {
        try {
            const footer = new window.FooterComponent();
            footer.init();
            window.appFooter = footer;
            console.log('Footer component initialized');
        } catch (error) {
            console.error('Error initializing footer component:', error);
        }
    }
    
    // 初始化侧边栏组件
    if (window.SidebarComponent) {
        try {
            const sidebar = new window.SidebarComponent();
            sidebar.init();
            window.appSidebar = sidebar;
            console.log('Sidebar component initialized');
        } catch (error) {
            console.error('Error initializing sidebar component:', error);
        }
    }
    
    // 初始化其他全局组件
    initForms();
    initCarousel();
    initLazyLoading();
}

/**
 * 初始化路由
 */
function initRouter() {
    if (window.router) {
        try {
            window.router.init({
                historyMode: false, // 使用hash模式，更简单的实现
                basePath: ''
            });
            
            // 注册路由
            window.router
                .add('/', () => {
                    console.log('Home page');
                    loadHomePage();
                })
                .add('/pages/about.html', () => {
                    console.log('About page');
                    // 已在about.html中处理
                })
                .add('/pages/contact.html', () => {
                    console.log('Contact page');
                    // 已在contact.html中处理
                })
                .add('/pages/post-template.html', (route) => {
                    console.log('Post page', route.query);
                    if (route.query.id) {
                        loadPostContent(route.query.id);
                    }
                });
            
            console.log('Router initialized');
        } catch (error) {
            console.error('Error initializing router:', error);
        }
    }
}

/**
 * 设置全局事件监听器
 */
function setupGlobalListeners() {
    console.log('Setting up global listeners...');
    
    // 处理平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80, // 考虑导航栏高度
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 窗口加载完成事件
    window.addEventListener('load', () => {
        console.log('Window fully loaded');
        // 隐藏加载指示器
        hideLoadingIndicator();
        
        // 执行页面加载后的动画
        animateOnLoad();
    });
    
    // 窗口大小变化事件
    window.addEventListener('resize', debounce(() => {
        console.log('Window resized');
        handleResponsiveLayout();
    }, 250));
    
    // 滚动事件处理
    window.addEventListener('scroll', throttle(() => {
        handleScrollEffects();
    }, 100));
}

/**
 * 处理页面特定逻辑
 */
function handlePageSpecificLogic() {
    const currentPage = window.location.pathname;
    console.log(`Handling logic for page: ${currentPage}`);
    
    // 根据当前页面执行特定逻辑
    if (currentPage.endsWith('/') || currentPage.endsWith('index.html')) {
        // 首页特定逻辑
        loadHomePageContent();
    } else if (currentPage.includes('/pages/post-template.html')) {
        // 文章详情页逻辑
        const urlParams = new URLSearchParams(window.location.search);
        const postId = urlParams.get('id');
        if (postId) {
            loadPostContent(postId);
        }
    } else if (currentPage.includes('/pages/contact.html')) {
        // 联系页表单处理
        setupContactForm();
    }
}

/**
 * 初始化表单处理
 */
function initForms() {
    console.log('Initializing forms...');
    
    // 全局表单验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            // 表单提交前的全局处理
            if (!this.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.add('was-validated');
                return false;
            }
            
            // 可以在这里添加表单提交前的其他处理
            this.classList.add('submitting');
        });
    });
}

/**
 * 初始化轮播图
 */
function initCarousel() {
    const carousel = document.querySelector('.carousel');
    if (carousel) {
        console.log('Initializing carousel...');
        // 简单的轮播图实现或使用现有库
        // 这里可以根据需要实现轮播功能
    }
}

/**
 * 初始化图片懒加载
 */
function initLazyLoading() {
    console.log('Initializing lazy loading...');
    
    // 检查浏览器是否支持IntersectionObserver
    if ('IntersectionObserver' in window) {
        const lazyImages = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const image = entry.target;
                    image.src = image.dataset.src;
                    image.removeAttribute('data-src');
                    image.classList.add('loaded');
                    imageObserver.unobserve(image);
                }
            });
        });
        
        lazyImages.forEach(image => {
            imageObserver.observe(image);
        });
    } else {
        // 降级处理
        const lazyImages = document.querySelectorAll('img[data-src]');
        lazyImages.forEach(image => {
            image.src = image.dataset.src;
            image.removeAttribute('data-src');
        });
    }
}

/**
 * 初始化页面过渡动画
 */
function initPageTransition() {
    console.log('Initializing page transitions...');
    
    // 显示页面加载指示器
    showLoadingIndicator();
    
    // 添加页面入场动画
    document.body.classList.add('page-loading');
    
    window.addEventListener('load', () => {
        setTimeout(() => {
            document.body.classList.remove('page-loading');
            document.body.classList.add('page-loaded');
        }, 300);
    });
}

/**
 * 加载首页内容
 */
async function loadHomePageContent() {
    console.log('Loading home page content...');
    
    try {
        // 获取文章列表
        const postsContainer = document.querySelector('.posts-container');
        if (postsContainer && window.api && window.api.getPosts) {
            const loadingState = document.createElement('div');
            loadingState.className = 'loading-state';
            loadingState.textContent = '加载文章中...';
            postsContainer.appendChild(loadingState);
            
            const result = await window.api.getPosts({ page: 1, limit: 10 });
            
            // 清空加载状态
            postsContainer.innerHTML = '';
            
            // 渲染文章列表
            renderPostList(postsContainer, result.posts);
            
            // 初始化分页
            initPagination(result);
        }
    } catch (error) {
        console.error('Error loading home page content:', error);
        showError('加载内容失败，请稍后重试');
    }
}

/**
 * 加载文章内容
 * @param {string} postId - 文章ID
 */
async function loadPostContent(postId) {
    console.log(`Loading post content for ID: ${postId}`);
    
    try {
        // 显示加载状态
        const postContent = document.querySelector('.post-content');
        if (postContent) {
            postContent.innerHTML = '<div class="loading-state">加载文章中...</div>';
        }
        
        // 获取文章详情
        if (window.api && window.api.getPostById) {
            const post = await window.api.getPostById(postId);
            
            // 渲染文章内容
            renderPostContent(post);
            
            // 加载相关文章
            if (post.categories) {
                loadRelatedPosts(postId, post.categories);
            }
        }
    } catch (error) {
        console.error('Error loading post content:', error);
        showError('加载文章失败');
    }
}

/**
 * 渲染文章列表
 * @param {HTMLElement} container - 容器元素
 * @param {Array} posts - 文章列表数据
 */
function renderPostList(container, posts) {
    if (!posts || posts.length === 0) {
        container.innerHTML = '<div class="no-posts">暂无文章</div>';
        return;
    }
    
    posts.forEach(post => {
        const postCard = document.createElement('article');
        postCard.className = 'post-card';
        
        // 文章HTML结构
        postCard.innerHTML = `
            <div class="post-content">
                <header class="post-header">
                    <h2 class="post-title">
                        <a href="/pages/post-template.html?id=${post.id}">${post.title}</a>
                    </h2>
                    <div class="post-meta">
                        <span class="post-date">${formatDate(post.date)}</span>
                        <span class="post-author">${post.author || '博主'}</span>
                        <span class="post-views">${post.views || 0} 阅读</span>
                    </div>
                </header>
                <div class="post-excerpt">${post.excerpt}</div>
                <footer class="post-footer">
                    <div class="post-categories">
                        ${post.categories?.map(cat => 
                            `<a href="/?category=${encodeURIComponent(cat)}" class="category">${cat}</a>`
                        ).join('')}
                    </div>
                    <a href="/pages/post-template.html?id=${post.id}" class="read-more">
                        阅读更多 <i class="icon-arrow-right"></i>
                    </a>
                </footer>
            </div>
        `;
        
        // 如果有缩略图，添加到卡片
        if (post.image) {
            const postThumbnail = document.createElement('div');
            postThumbnail.className = 'post-thumbnail';
            postThumbnail.innerHTML = `<a href="/pages/post-template.html?id=${post.id}">
                <img src="${post.image}" alt="${post.title}">
            </a>`;
            postCard.prepend(postThumbnail);
        }
        
        container.appendChild(postCard);
    });
}

/**
 * 渲染文章内容
 * @param {Object} post - 文章数据
 */
function renderPostContent(post) {
    const postHeader = document.querySelector('.post-header');
    const postContent = document.querySelector('.post-content');
    
    if (postHeader) {
        postHeader.innerHTML = `
            <h1 class="post-title">${post.title}</h1>
            <div class="post-meta">
                <span class="post-date">${formatDate(post.date)}</span>
                <span class="post-author">${post.author || '博主'}</span>
                <span class="post-views">${post.views || 0} 阅读</span>
                <span class="post-read-time">${calculateReadTime(post.content)} 阅读时间</span>
            </div>
            <div class="post-categories">
                ${post.categories?.map(cat => 
                    `<a href="/?category=${encodeURIComponent(cat)}" class="category">${cat}</a>`
                ).join('')}
            </div>
            ${post.image ? 
                `<div class="post-featured-image">
                    <img src="${post.image}" alt="${post.title}">
                </div>` : ''
            }
        `;
    }
    
    if (postContent) {
        postContent.innerHTML = `
            <div class="post-body">${formatContent(post.content)}</div>
            <div class="post-tags">
                ${post.tags?.map(tag => 
                    `<a href="/?tag=${encodeURIComponent(tag)}" class="tag">${tag}</a>`
                ).join('')}
            </div>
        `;
    }
}

/**
 * 加载相关文章
 * @param {string} postId - 当前文章ID
 * @param {Array} categories - 当前文章分类
 */
async function loadRelatedPosts(postId, categories) {
    try {
        const relatedContainer = document.querySelector('.related-posts');
        if (relatedContainer && window.api && window.api.getRelatedPosts) {
            const relatedPosts = await window.api.getRelatedPosts(postId, categories, 3);
            
            if (relatedPosts && relatedPosts.length > 0) {
                relatedContainer.innerHTML = '<h3 class="section-title">相关文章</h3><div class="related-posts-list"></div>';
                const listContainer = relatedContainer.querySelector('.related-posts-list');
                
                relatedPosts.forEach(post => {
                    const postItem = document.createElement('article');
                    postItem.className = 'related-post-item';
                    postItem.innerHTML = `
                        <a href="/pages/post-template.html?id=${post.id}">
                            ${post.image ? 
                                `<img src="${post.image}" alt="${post.title}" class="related-post-thumbnail">` : ''
                            }
                            <h4 class="related-post-title">${post.title}</h4>
                            <span class="related-post-date">${formatDate(post.date)}</span>
                        </a>
                    `;
                    listContainer.appendChild(postItem);
                });
            }
        }
    } catch (error) {
        console.error('Error loading related posts:', error);
    }
}

/**
 * 初始化分页
 * @param {Object} pagination - 分页数据
 */
function initPagination(pagination) {
    const paginationContainer = document.querySelector('.pagination');
    if (!paginationContainer) return;
    
    const { page, totalPages } = pagination;
    
    if (totalPages <= 1) {
        paginationContainer.style.display = 'none';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页
    if (page > 1) {
        paginationHTML += `<a href="/?page=${page - 1}" class="prev">上一页</a>`;
    }
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === page) {
            paginationHTML += `<span class="current">${i}</span>`;
        } else {
            paginationHTML += `<a href="/?page=${i}">${i}</a>`;
        }
    }
    
    // 下一页
    if (page < totalPages) {
        paginationHTML += `<a href="/?page=${page + 1}" class="next">下一页</a>`;
    }
    
    paginationContainer.innerHTML = paginationHTML;
}

/**
 * 设置联系表单
 */
function setupContactForm() {
    const contactForm = document.querySelector('#contact-form');
    if (contactForm) {
        contactForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.textContent;
            
            // 禁用提交按钮
            submitButton.disabled = true;
            submitButton.textContent = '发送中...';
            
            try {
                const formData = new FormData(this);
                const data = Object.fromEntries(formData.entries());
                
                // 使用API提交表单
                if (window.api && window.api.submitContactForm) {
                    const result = await window.api.submitContactForm(data);
                    
                    if (result.success) {
                        // 显示成功消息
                        showMessage('success', result.message);
                        // 重置表单
                        this.reset();
                    } else {
                        showMessage('error', result.message);
                    }
                }
            } catch (error) {
                console.error('Error submitting contact form:', error);
                showMessage('error', '发送失败，请稍后重试');
            } finally {
                // 恢复提交按钮
                submitButton.disabled = false;
                submitButton.textContent = originalButtonText;
            }
        });
    }
}

/**
 * 处理滚动效果
 */
function handleScrollEffects() {
    const scrollPosition = window.scrollY;
    
    // 可以在这里添加滚动相关的动画和效果
    
    // 检测元素是否进入视口并添加动画
    document.querySelectorAll('.animate-on-scroll').forEach(element => {
        const elementTop = element.getBoundingClientRect().top;
        const elementVisible = 150;
        
        if (elementTop < window.innerHeight - elementVisible) {
            element.classList.add('animate-in');
        }
    });
}

/**
 * 处理响应式布局
 */
function handleResponsiveLayout() {
    const viewportWidth = window.innerWidth;
    
    if (viewportWidth < 768) {
        document.body.classList.add('mobile-view');
        document.body.classList.remove('tablet-view', 'desktop-view');
    } else if (viewportWidth < 1024) {
        document.body.classList.add('tablet-view');
        document.body.classList.remove('mobile-view', 'desktop-view');
    } else {
        document.body.classList.add('desktop-view');
        document.body.classList.remove('mobile-view', 'tablet-view');
    }
}

/**
 * 显示加载指示器
 */
function showLoadingIndicator() {
    const loader = document.createElement('div');
    loader.className = 'page-loader';
    loader.innerHTML = '<div class="spinner"></div>';
    document.body.appendChild(loader);
}

/**
 * 隐藏加载指示器
 */
function hideLoadingIndicator() {
    const loader = document.querySelector('.page-loader');
    if (loader) {
        loader.classList.add('fade-out');
        setTimeout(() => {
            loader.remove();
        }, 500);
    }
}

/**
 * 显示消息
 * @param {string} type - 消息类型 (success, error, info)
 * @param {string} message - 消息内容
 */
function showMessage(type, message) {
    const messageContainer = document.createElement('div');
    messageContainer.className = `message message-${type}`;
    messageContainer.textContent = message;
    
    document.body.appendChild(messageContainer);
    
    // 自动关闭
    setTimeout(() => {
        messageContainer.classList.add('fade-out');
        setTimeout(() => {
            messageContainer.remove();
        }, 500);
    }, 3000);
}

/**
 * 显示错误
 * @param {string} message - 错误消息
 */
function showError(message) {
    const errorContainer = document.createElement('div');
    errorContainer.className = 'error-message';
    errorContainer.innerHTML = `
        <p>${message}</p>
        <button class="retry-btn">重试</button>
    `;
    
    // 替换内容区域或添加到特定位置
    const mainContent = document.querySelector('main');
    if (mainContent) {
        mainContent.appendChild(errorContainer);
    }
    
    // 重试按钮事件
    const retryBtn = errorContainer.querySelector('.retry-btn');
    retryBtn.addEventListener('click', () => {
        errorContainer.remove();
        location.reload();
    });
}

/**
 * 页面加载动画
 */
function animateOnLoad() {
    // 可以在这里添加页面加载完成后的动画
    document.querySelectorAll('.fade-in').forEach((element, index) => {
        setTimeout(() => {
            element.classList.add('loaded');
        }, index * 100);
    });
}

/**
 * 格式化日期
 * @param {string} dateString - 日期字符串
 * @returns {string} 格式化后的日期
 */
function formatDate(dateString) {
    try {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    } catch (error) {
        return dateString;
    }
}

/**
 * 计算阅读时间
 * @param {string} content - 文章内容
 * @returns {number} 阅读时间（分钟）
 */
function calculateReadTime(content) {
    const wordsPerMinute = 200;
    const wordCount = content.trim().split(/\s+/).length;
    return Math.ceil(wordCount / wordsPerMinute);
}

/**
 * 格式化文章内容
 * @param {string} content - 文章内容
 * @returns {string} 格式化后的HTML
 */
function formatContent(content) {
    // 简单的内容格式化，可以根据需要扩展
    return content
        .replace(/\n\n/g, '<br><br>') // 双换行转成br标签
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
        .replace(/\*(.*?)\*/g, '<em>$1</em>'); // 斜体
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间
 * @returns {Function} 防抖后的函数
 */
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

/**
 * 节流函数
 * @param {Function} func - 要执行的函数
 * @param {number} limit - 限制时间
 * @returns {Function} 节流后的函数
 */
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const context = this;
        const args = arguments;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 导出全局方法和变量
window.app = {
    initComponents,
    handleScrollEffects,
    showMessage,
    loadPostContent
};

console.log('Main JavaScript initialized');